package cn.kgc.springmvc.handlers;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 课工场
 * @date 2024/2/29
 * @description  定义全局异常处理类  springmvc中提供的一种全局异常处理方案
 *
 * 1.定义一个普通类
 * 2.在类中编写不同的方法实现对不同异常的处理方案   @ExceptionHandler
 * 3.在类上添加ControllerAdvice 注解标识当前类是全局异常处理类

 *
 * @RestControllerAdvice  = @ControllerAdvice  +  @ResponseBody
 */

// @ResponseBody
// @ControllerAdvice

@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(Exception.class)
    public Map<String,Object> otherExceptionHandler(Exception e){
        System.out.println(e.getMessage());
        e.printStackTrace();
        HashMap<String, Object> result = new HashMap<String, Object>();
        result.put("code",500);
        result.put("message","服务器繁忙,请稍后再试");

        return result;
    }

    @ExceptionHandler({ArithmeticException.class, NullPointerException.class})
    public  Map<String,Object>  arithmeticExceptionHandler(Exception e){

        HashMap<String, Object> result = new HashMap<String, Object>();
        result.put("code",500);
        result.put("message","数学运算异常");
        return result;
    }
}
